$(document).ready(function () {
    validateUser();
});
var ipAddress="localhost";
var goods;

//查询某个用户的购物车信息
var queryAllGoodsInCart=function (){
    var accountId=getUrlParms("accountId");
    accountId=1;
    $.ajax({
        url: "http://"+ipAddress+":8003/cart/carts/"+accountId,
        type: "GET",
        async: true,
        data: null,
        contentType:"application/json",
        dataType: "json",
        success:function (data) {
            goods=data.data;
            console.log(" data cartVOList====  "+data.data);
            if (data.message=="查询成功！没有查询到数据！"){
                layer.msg("您的购物车还是空空如也哦！快去购物吧！");
                $("#tableHead").append(
                    "<div style='margin: 40px auto 20px auto; width:100%;height:100px;font:text-align:center;vertical-align: center'>"+
                    "<p style='text-align:center;font-size: medium;color: grey;vertical-align: center'>您的购物车还是空空如也哦！快去购物吧！</p>"+
                    "</div>"
                );

            }
            $.each(data.data, function (index, value) {
                var eachTotal=value.cart.price*value.cart.number;
                $("#tableHead").append(
                    "<div class='content2 center' id='"+index+"'>"+
                        "<div class='sub_content fl'>"+
                            "<input type='checkbox' value='quanxuan' class='quanxuan' name='checkbox' id=''+index'' onclick='count()'>"+
                            "<span id='cartId' style='display:none;'>"+value.cart.id+"</span>"+
                        "</div>"+
                        "<div class='sub_content fl'><a href='./goodsDetail.html?keywords="+value.goodsVO.goodsName+"'><img src='"+value.goodsVO.picture+"' width='50px'></a></div>"+
                        "<div class='sub_content fl ft20'>"+value.goodsVO.skuName+"</div>"+
                        "<div class='sub_content fl'> <span name='price' id='price"+index+"'>"+value.cart.price+"</span>元</div>"+
                        "<div class='sub_content fl'>"+
                            "<input class='shuliang' type='number' value="+value.cart.number+" step='1' min='1' max='"+value.goodsVO.limitedNumber+"' onchange ='updateNum(this)'  oninput = \"value=value.replace(/[^\\d]/g,'')\">"+
                            "<span id='stock' style='display:none' >"+value.goodsVO.stock+"</span>"+
                            "<span id='limitedNumber' style='display:none' >"+value.goodsVO.limitedNumber+"</span>"+
                        "</div>"+
                        "<div class='sub_content fl' style=\"width:auto;align:center\" > <span name='eachTotal' id='eachTotal"+index+"'>"+eachTotal+"</span>元</div>"+
                        "<div class='sub_content fl' style=\"align:center\"><a id='"+value.cart.id+"' onclick='deleteGoodsInCart(this)'>×</a></div>"+
                        "<div class='clear'></div>"+
                    "</div>"
                );

            console.log("value.goodsVO.goodsName:==="+value.goodsVO.goodsName);

            });
            selectAll();
        },
        error:function () {
            layer.alert("加载失败!");
        }
    });
}

//删除某个用户的购物车的商品
var deleteGoodsInCart=function (obj){
    layer.confirm('确定删除该商品吗？', {
        btn: ['确认', '取消']
    }, function () {
        //layer.msg("yyyyyyy");
        var cartId = obj.id;

        $.ajax({
            url: "http://" + ipAddress + ":8003/cart/cart/" + cartId,
            type: "DELETE",
            async: true,
            data: null,
            contentType: "application/json",
            dataType: "json",
            success: function (data) {
                console.log(" data cartVOList====  " + data.data);
                if (data.success == true) {
                    $(obj).parent().parent().remove();
                    layer.msg("商品移除成功!");
                    count();
                }else{
                    layer.msg(""+data.message);
                }
            },
            error: function () {
                layer.msg("商品移除失败!" + data.data.message);
            }
        });

        //在function中加ajax请求时，若不加return false则不能关闭confirm
        return false;
    });


};

//全选中和取消全选
function selectAll(){
    if ($("#select-all").is(":checked")) {
        $("[name='checkbox']").prop("checked", true);
        $("#qxVal").html("取消全选");
    } else {
        $("[name='checkbox']").prop("checked", false);
        $("#qxVal").html("全选");
    }
    count();
}

//计算选中的个数和总的个数
function count() {
    var allChecked = 0;//所有选中checkbox的数量
    var all = 0;//所有checkbox的数量
    var totalFee = Number(0); //所选中商品的总价
    $("input:checkbox[name='checkbox']").each(function (i) {
        all++;
        if ($(this).is(":checked")) {
            allChecked++;
            totalFee+=Number($("#eachTotal"+i).html());
        }
    });

    if(all!=0) {
        if (all == allChecked) {
            $("#select-all").prop("checked", true);
            $("#qxVal").html("取消全选");
        } else {
            $("#select-all").prop("checked", false);
            $("#qxVal").html("全选");
        }
    }

    $("#allItemNumber").html(all);
    $("#selectedNum").html(allChecked);
    $("#totalFee").html(totalFee);
}

//更改购买数量
var updateNum=function(obj){
    //购买数量
    var number=Number(obj.value);
    var price=$(obj).parent().prev().children("span").html();
    console.log("number==ddadddd="+number);
    if(number==0){
        $(obj).val(1);
        number=1;
        layer.msg("购买数量最少是1！");
        //商品总价
        var eachTotal=Number(price)*Number(number);
        $(obj).parent().next().children("span").html(eachTotal);
        //count();
    }
    //商品库存量
    var stock=Number($(obj).next().html());
    //限购额
    var limitedNumber=Number($(obj).next().next().html());
    console.log("库存："+stock);
    console.log("number=="+number);
    console.log("limitedNumber："+limitedNumber);

    if (number>stock){
        if(stock<=limitedNumber){
            $(obj).val(stock);
            number=stock;
            var eachTotal=Number(price)*Number(number);
            $(obj).parent().next().children("span").html(eachTotal);
            //count();
        }else{
            $(obj).val(limitedNumber);
            number=limitedNumber;
            var eachTotal=Number(price)*Number(number);
            $(obj).parent().next().children("span").html(eachTotal);
            //count();
        }
        layer.msg("库存不够了！！！");
    }else if (number>limitedNumber){
        $(obj).val(limitedNumber);
        number=limitedNumber;
        var eachTotal=Number(price)*Number(number);
        $(obj).parent().next().children("span").html(eachTotal);
        layer.msg("该商品限购"+limitedNumber+"件！");
        //count();
    }else{
        //商品总价
        var eachTotal=Number(price)*Number(number);
        $(obj).parent().next().children("span").html(eachTotal);
        //count();
    }
    count();
    //购物车信息id
    var cartId=$(obj).parent().next().next().children("a").attr("id");

    //封装成对象提交
    var cart = {
        id:cartId,
        number:number
    };
    $.ajax({
        url: "http://"+ipAddress+":8003/cart/cart/",
        type: "PUT",
        async: true,
        data: JSON.stringify(cart),
        contentType:"application/json",
        dataType: "json",
        success:function (data) {
            console.log(" data cartVOList====  "+data.data);
            //layer.msg("更新成功!");
        },
        error:function () {
            layer.message("更新失败!"+data.data.message);
        }
    });

};

//验证用户是否登录
var validateUser=function(){
    $.ajax({
        //url: "http://" + ipAddress + ":8080/user/get_user_info",
        url: "http://" + ipAddress + ":8004/orderInfo/checkAccount",
        type: "GET",
        async: false,
        data: null,
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            console.log(" data====  " + data);
            if (data.message !="success") {
                layer.msg("请先登录！");
                setTimeout(function () {//两秒后跳转
                    window.location.href = "./login.html"
                }, 1000);
            }else {
                queryAllGoodsInCart();
            }
        },
        error: function () {
            layer.msg("后台服务器开小差了...")
        }
    })
};

//去下单
var checkout= function () {
    var cartIdList =new Array();
    if($("#selectedNum").html()==0){
        layer.msg("请先选择您要下单的商品！");
    }else{
        $("input:checkbox[name='checkbox']").each(function (i) {
            if ($(this).is(":checked")) {
                var cartId=$(this).next().html();
                console.log("cartId="+cartId);
                cartIdList.push(cartId);
            }
        });
        window.location.href="./checkout.html?cartIdList="+cartIdList;
        console.log("arr=="+cartIdList);
    }
}



